package com.pointstar.dp.modules.project.util;

/**
 * @author 朱科睿
 * @date 2021-08-28
 */
public class IpUtil {

    private IpUtil() {
    }

    /**
     * 比较IP大小
     *
     * @param ip1 ip1
     * @param ip2 ip2
     * @return result
     */
    public static int compareIpV4s(String ip1,String ip2) {
        int result = 1;
        // 获取ip1的32bit值
        int ipValue1 = getIpV4Value(ip1);
        // 获取ip2的32bit值
        int ipValue2 = getIpV4Value(ip2);
        if(ipValue1 > ipValue2)
        {
            result =  -1;
        }
        return result;
    }

    public static int getIpV4Value(String ipOrMask) {
        byte[] addr = getIpV4Bytes(ipOrMask);
        int address1  = addr[3] & 0xFF;
        address1 |= ((addr[2] << 8) & 0xFF00);
        address1 |= ((addr[1] << 16) & 0xFF0000);
        address1 |= ((addr[0] << 24) & 0xFF000000);
        return address1;
    }

    public static byte[] getIpV4Bytes(String ipOrMask) {
        try{
            String[] addrs = ipOrMask.split("\\.");
            int length = addrs.length;
            byte[] addr = new byte[length];
            for (int index = 0; index < length; index++)
            {
                addr[index] = (byte) (Integer.parseInt(addrs[index]) & 0xff);
            }
            return addr;
        }catch (Exception ignored){
        }
        return new byte[4];
    }
}
